package com.training.service;

import com.training.dto.CommentDisplayDto;
import com.training.entity.Comment;
import com.training.entity.CommentReply;
import com.training.entity.Student;
import com.training.mapper.CommentMapper;
import com.training.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentService {

    private final CommentMapper commentMapper;
    private final StudentMapper studentMapper;

    @Autowired
    public CommentService(CommentMapper commentMapper, StudentMapper studentMapper) {
        this.commentMapper = commentMapper;
        this.studentMapper = studentMapper;
    }

    /**
     * Add a new comment to the database.
     * Corresponds to FR-KC-4.
     * @param comment The Comment object to be added.
     * @return true if the comment was added successfully, false otherwise.
     */
    @Transactional
    public boolean addComment(Comment comment) {
        // Basic validation
        if (comment.getCourseId() == null || comment.getUserId() == null ||
                comment.getContent() == null || comment.getContent().trim().isEmpty()) {
            throw new IllegalArgumentException("评论内容和所属课程、学生ID不能为空。");
        }

        // Validate content length (example: 10 to 500 characters)
        if (comment.getContent().length() < 10 || comment.getContent().length() > 500) {
            throw new IllegalArgumentException("评论内容长度必须在10到500个字符之间。");
        }

        // Validate rating (1-5)
        if (comment.getRating() == null || comment.getRating() < 1 || comment.getRating() > 5) {
            throw new IllegalArgumentException("评分必须在1到5之间。");
        }

        comment.setCreateTime(LocalDateTime.now());
        comment.setUpdateTime(LocalDateTime.now());
        comment.setDeleted(0); // Default to not deleted

        return commentMapper.insertComment(comment) > 0;
    }

    /**
     * Get all comments for a specific course, including student names.
     * @param courseId The ID of the course.
     * @return A list of CommentDisplayDto objects.
     */
    public List<CommentDisplayDto> getCommentsByCourseId(Long courseId) {
        List<Comment> comments = commentMapper.findCommentsByCourseId(courseId);
        List<CommentDisplayDto> commentDisplayDtos = new ArrayList<>();

        for (Comment comment : comments) {
            CommentDisplayDto dto = new CommentDisplayDto(comment);

            // Get student information to display student name
            if (comment.getUserId() != null) {
                Student student = studentMapper.findById(comment.getUserId());
                if (student != null) {
                    dto.setStudentName(student.getStuName());
                } else {
                    dto.setStudentName("未知学生"); // Fallback if student not found
                }
            } else {
                dto.setStudentName("未知用户"); // Fallback if userId is null
            }
            commentDisplayDtos.add(dto);
        }
        return commentDisplayDtos;
    }

    /**
     * Update an existing comment.
     * @param comment The Comment object with updated information.
     * @return true if the comment was updated successfully, false otherwise.
     */
    @Transactional
    public boolean updateComment(Comment comment) {
        if (comment.getId() == null) {
            throw new IllegalArgumentException("评论ID不能为空。");
        }
        if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
            throw new IllegalArgumentException("评论内容不能为空。");
        }
        if (comment.getRating() == null || comment.getRating() < 1 || comment.getRating() > 5) {
            throw new IllegalArgumentException("评分必须在1到5之间。");
        }
        comment.setUpdateTime(LocalDateTime.now()); // Update timestamp
        return commentMapper.updateComment(comment) > 0;
    }

    /**
     * Logically delete a comment.
     * @param id The ID of the comment to delete.
     * @return true if the comment was logically deleted successfully, false otherwise.
     */
    @Transactional
    public boolean deleteComment(Long id) {
        return commentMapper.deleteComment(id) > 0;
    }

    /**
     * Find a comment by its ID.
     * @param id Comment ID
     * @return Comment object, null if not found or logically deleted
     */
    public Comment getCommentById(Long id) {
        return commentMapper.findCommentById(id);
    }

    public List<CommentDisplayDto> getCommentsByTeacherId(Long teacherId) {
        return commentMapper.findCommentsByTeacherId(teacherId);
    }

    /**
     * 教师添加回复
     * @param reply 包含回复内容、教师ID、评论ID的对象
     * @param userId 当前操作的教师所对应的用户ID
     */
    @Transactional
    public void addReply(CommentReply reply, Long userId) {
        if (reply.getContent() == null || reply.getContent().trim().isEmpty()) {
            throw new IllegalArgumentException("回复内容不能为空。");
        }
        if (userId == null) {
            throw new IllegalArgumentException("无法确定回复的用户ID，操作失败。");
        }

        // --- 这是关键的修复 ---
        // 1. 设置回复的用户ID
        reply.setUserId(userId);
        // 2. 设置创建时间等默认值
        reply.setCreateTime(LocalDateTime.now());
        reply.setDeleted(0);

        commentMapper.addReply(reply);
    }
}